'use strict'

const Service = require('egg').Service

class AdminUserService extends Service {
  // 注册
  async register(params) {
    const { ctx, app } = this
    const user = await app.model.AdminUser.findOne({ where: { username: params.username } })
    if (user) ctx.throw(400, '用户名已存在')
    return app.model.AdminUser.create(params)
  }
  // 根据用户id查找用户
  async findById(id) {
    return await this.app.model.AdminUser.findOne({
      where: {
        id
      },
      attributes: {
        exclude: ['password']
      }
    })
  }
  //获取用户对应的角色
  async getRole(id) {
    const { app } = this
    return app.model.AdminUser.findAll({
      include: [
        {
          model: app.model.Role,
          through: {
            attributes: []
          }
        }
      ],
      attributes: [],
      where: {
        id
      }
    })
  }
  // 获取角色对应的权限
  getPermissions(rid) {
    const { app } = this
    return app.model.Role.findAll({
      include: [
        {
          model: app.model.Permissions,
          through: {
            attributes: []
          }
        }
      ],
      attributes: [],
      where: {
        id: rid
      }
    })
  }
}

module.exports = AdminUserService
